import Vue from 'vue'
import Vuex from 'vuex'
import {login, register} from '@/api/user'
import { setStore, getStore, removeStore } from '@/utils/storage'

Vue.use(Vuex);

const state = {
  // 用户信息

  username: '',
  avatar: '',
  nickname: '',
  token: ''

};

const mutations = {
  SET_USER_INFO: (state, userInfo) => {
    state.username = userInfo.username
    state.token = userInfo.token
    state.nickname = userInfo.nickname
    state.avatar = userInfo.avatar
  },

  CLEAR_USER_INFO:()=>{
    state.username = ''
    state.token = ''
    state.nickname = ''
    state.avatar = ''
  }
};

const actions = {
  login({commit}, info) {
    return new Promise((resolve, reject) => {
      login(info).then(r1 => {
        console.log("登陆》",r1)
        commit('SET_USER_INFO', r1.data)
        setStore('token', r1.data.token)
        setStore('username', r1.data.username)
        setStore('nickname', r1.data.nickname)
        setStore('avatar', r1.data.avatar)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  register({commit}, info) {
    return new Promise((resolve, reject) => {
      register(info).then(r1 => {
        console.log("注册》",r1)
        commit('SET_USER_INFO', r1.data)
        setStore('token', r1.data.token)
        setStore('username', r1.data.username)
        setStore('nickname', r1.data.nickname)
        setStore('avatar', r1.data.avatar)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  /**权限过期，删除信息*/
  clearInfo({commit}) {
    return new Promise((resolve) => {
      console.log("清楚信息")
        commit('CLEAR_USER_INFO')
        removeStore('token')
        removeStore('username')
        removeStore('nickname')
        removeStore('avatar')
        resolve()
    })
  },

  // getUserInfo({commit}) {
  //   // return new Promise(resolve => {
  //   //   getUserInfo().then(r1 => {
  //   //     console.log("这次的信息是：",r1.data)
  //   //     if(r1.data) {
  //   //       commit('SET_USER_INFO', r1.data)
  //   //     }
  //   //     //如果没有登录返回的是null
  //   //     resolve()
  //   //   })
  //   // })
  //   return new Promise((resolve, reject) => {
  //     getUserInfo().then(r1 => {
  //           console.log("这次的信息是：",r1.data)
  //           if(r1.data) {
  //             commit('SET_USER_INFO', r1.data)
  //           }
  //           //如果没有登录返回的是null
  //           resolve()
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // }
};

const getters = {
  token: state => state.token,
  username: state => state.username,
  avatar: state => state.avatar,
};

export default new Vuex.Store({
  state,
  getters,
  mutations,
  actions,
});
